//
//  YPGlobal.swift
//  YPSwift
//
//  Created by jerry on 2020/5/23.
//  Copyright © 2020 ogawa. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyUserDefaults

extension DefaultsKeys {
    ///缓存用户的主键id
    static let userid = DefaultsKey<String>("com.ypcontext.userid", defaultValue: "")
    ///缓存token
    static let token = DefaultsKey<String>("com.ypcontext.token", defaultValue: "")
    ///用户账号
    static let userName = DefaultsKey<String>("com.ypcontext.username", defaultValue: "")
    ///登录密码
    static let password = DefaultsKey<String>("com.ypcontext.password", defaultValue: "")
    ///是否记住
    static let isRember = DefaultsKey<Bool>("com.ypcontext.isrember", defaultValue: false)
}

public struct YPGlobal {
    public static var shared = YPGlobal()
    private var disposeBag = DisposeBag()
    
    private init() { }
    
    public var user: YPContextUser_m?
    
    ///更新用户信息
    public static func updateUserModel(_ user:YPContextUser_m) -> Void {
        YPGlobal.shared.user = user
        Defaults[key: DefaultsKeys.userid] = user.userid
        Defaults[key: DefaultsKeys.token] = user.token
        updateToken()
        /// 发送退出通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: YPEnvs.notificationKey.loginSuccess), object: user)
    }
    
    /// 更新token
    public static func updateToken() {
        if let user = YPGlobal.shared.user {
            YPNetWorkAPI.sharedInstance.headers["token"] = user.token
        }
    }
    
    /// 退出登录 ， 清空用户信息
    public static func logout() {
        YPGlobal.shared.user  = nil
        Defaults.remove(DefaultsKeys.userid)
        Defaults.remove(DefaultsKeys.token)
//        YPNetWorkAPI.sharedInstance.headers.removeValue(forKey: "token")
        // 发送退出通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: YPEnvs.notificationKey.logoutSuccess), object: nil)
    }
    
    public static func isRember() -> Bool {
        return Defaults[key: DefaultsKeys.isRember]
    }
    
    public static func updateIsRember( _ isRember:Bool) {
        Defaults[key: DefaultsKeys.isRember] = isRember
    }
    
    public static func userName() -> String {
        return Defaults[key: DefaultsKeys.userName]
    }
    
    public static func updateUserName( _ userName:String) {
        Defaults[key: DefaultsKeys.userName] = userName
    }
    
    public static func password() -> String {
        return Defaults[key: DefaultsKeys.password]
    }
    
    public static func updatePassword( _ password:String) {
        Defaults[key: DefaultsKeys.password] = password
    }
    
    //在发起通过token获取用户对象之前，读取本地缓存的token然后更新header中的token
    static func updateHeaderTokenFromCache () {
        if let user = YPGlobal.shared.user {
            YPNetWorkAPI.sharedInstance.headers["token"] = user.token
        } else {
            let token = Defaults[key: DefaultsKeys.token]
            if token.length > 0 {
                YPNetWorkAPI.sharedInstance.headers["token"] = token
            }
        }
    }
    
    //根据缓存的token更新用户对象
    public func updateUserFromService () {
        YPGlobal.updateHeaderTokenFromCache()
        Observable.just(YPGlobalApi.correctionuser)
            .emeRequestApiForObj(YPContextUser_m.self)
            .subscribe(onNext: { (result) in
                switch result {
                case .success(let user):
                    //登陆成功就更新上下文中的登陆对象
                    YPGlobal.updateUserModel(user)
                case .failure(_): break}
            })
            .disposed(by: disposeBag)
    }
    
}

public enum YPGlobalApi {
    /// 根据token校正客户端的用户对象
    case correctionuser
}

extension YPGlobalApi: TargetType {
    
    //请求路径
    public var path: String {
        switch self {
        case .correctionuser:
            return "user/correctionuser"
        }
    }
    
    //设置请求方式 get post等
    public var method: HTTPMethod {
        switch self {
        default:
            return .get
        }
    }
    
    /// 设置请求参数
    public var parameters: Parameters? {
        switch self {
        default:
            return nil
        }
    }
    
}
